package com.ansion.basedb.dao.helper;

import android.os.Bundle;
import android.text.TextUtils;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.UserLogicDao;
import com.ansion.basedb.dao.model.UserModel;
import com.ansion.basedb.notify.UserChangeNotifier;
import com.ansion.constant.BConstant;
import com.ansion.log.VLog;
import com.ansion.string.StringUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ThreadUtil;
import com.ansion.utils.ValueSafeTransfer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Andre
 */
public class UserCacheServiceMgr {

    private HashSet<Long> needSyncUidSet = new HashSet<Long>();
    private static UserCacheServiceMgr s_ins;
    private Timer timer;

    private static UserCacheServiceMgr getInstance() {
        if (null != s_ins) {
            return s_ins;
        }
        synchronized (UserCacheServiceMgr.class) {
            if (null != s_ins) {
                return s_ins;
            }
            s_ins = new UserCacheServiceMgr();
            return s_ins;
        }
    }

    UserCacheServiceMgr() {


    }

    /***
     * 只在使用的时候启动timer，不使用不启动timer
     */
    synchronized void startTimerIfNeed() {
        //doRealSyncUserProfile内部做了防抖操作，所以这里也不存在任务积压一起执行的问题
        if (timer == null) {
            VLog.stopD("APP_START", "%s start user cache timer", "APP_START");
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    try {
                        doRealSyncUserProfile();
                    } catch (Exception e) {
                        VLog.e("AZusNet", e);
                    }
                }
            }, 1000, 1000);
        }
    }


    void doRealSyncUserProfile(List<Long> uids) {
        if (null == uids || uids.size() == 0) {
            return;
        }

        VLog.e("TAG_SOCKET", "start doRealSyncUserProfile -> method: accountproxy.getSimpleBabaAccountList");

        // 从服务器去加载Profile
    }


    private long lastSyncSendTime = 0;

    synchronized void doRealSyncUserProfile() throws Exception {
        if (System.currentTimeMillis() - lastSyncSendTime < 1000) {
            return;
        }

        lastSyncSendTime = System.currentTimeMillis();

        synchronized (this) {
            if (needSyncUidSet.size() == 0) {
                return;
            }
            Iterator<Long> itr = needSyncUidSet.iterator();
            ArrayList<Long> uids = new ArrayList<Long>();
            while (itr.hasNext()) {
                long uid = itr.next();
                uids.add(uid);
                if (uids.size() >= 50) {
                    doRealSyncUserProfile(uids);
                    uids.clear();
                }
            }
            doRealSyncUserProfile(uids);
            needSyncUidSet.clear();
        }

    }

    void addSyncUid(long uid) {
        startTimerIfNeed();
        synchronized (this) {
            if (isValidateUid(uid)) {
                needSyncUidSet.add(uid);
            }
        }
    }

    private boolean isValidateUid(long uid) {
        return (uid != 0 &&
                uid != ContactUtil.BOTIM_FILE_ASSISTANT_ID);
    }


    // 只在收到消息时允许调用
    public static void saveUserFromMessage(UserModel user, Boolean isVip, boolean isVoip, Bundle params) {
        if (null == user) {
            return;
        }
        if (user.getUserId() == LoginedUserMgr.getUserId()) {
            return;
        }
        if ((TextUtils.isEmpty(user.getNickName()) || TextUtils.isEmpty(user.getAvatarUrl())) && ContactUtil.isOAAccount(user.getUserId())) {
            if (VLog.OPEN_LOG)
                VLog.e("TAG_OA", "saveUserFromMessag get empty name or avatar;uid:" + user.getUserId());
        }

        // 保存数据库
        UserLogicDao userDao = UserHelper.getUserDBDao();
        if (null == userDao) {
            return;
        }
        long userId = user.getUserId();
        UserModel dbUser = null;
        if (ContactUtil.isOAAccount(userId)) {
            dbUser = userDao.getUserOnly(userId);
        } else {
            dbUser = userDao.getUser(userId);
        }

        boolean bNeedGetProfile = false;
        boolean avatarChange = false;
        boolean vipChange = false;
        String uidStr = ValueSafeTransfer.stringValue(userId);
        if (dbUser == null) {
            dbUser = user;
            bNeedGetProfile = true;
            dbUser.setOaid(user.getOaid());
            dbUser.setVip(user.isVip());
            dbUser.setNickName(user.getNickName());
            dbUser.setAvatarUrl(user.getAvatarUrl());
            userDao.saveFromMessage(dbUser, isVoip);

            // 计算变更
            if (isVip != null) {
                //vip从false变true
                vipChange = (isVip == true);
            }
            //从无变为有头像
            avatarChange = !TextUtils.isEmpty(dbUser.getAvatarUrl());

        } else {//只要原来的db里面有，则只更新vip,nickName,oaId和avatar，原来的逻辑会出现收到公众号消息oa相关字段被清空
//			 nameChange = !StringUtils.stringIsEqual(dbUser.getNickName(),user.getNickName());
            if (isVip != null) {
                vipChange = (dbUser.isVip() != isVip);
            }
            avatarChange = !StringUtils.stringIsEqual(dbUser.getAvatarUrl(), user.getAvatarUrl());

            //有NickName且与db不一样
            boolean nameChange = !TextUtils.isEmpty(user.getNickName()) && !StringUtils.stringIsEqual(dbUser.getNickName(), user.getNickName());
            dbUser = dbUser.clone();
            if (!TextUtils.isEmpty(user.getNickName())) {
                dbUser.setNickName(user.getNickName());
            }
            if (!TextUtils.isEmpty(user.getOaid())) {
                dbUser.setOaid(user.getOaid());
            }
            if (!TextUtils.isEmpty(user.getAvatarPrevUrl())) {//目前服务器不会把用户头像送过来，而且save之前usermodel也没有设置头像
                // 服务器把头像送回来了
                dbUser.setAvatarUrl(user.getAvatarUrl());
            }

            //改为Boolean，避免server端没有返回vip导致把客户端本地的vip给清掉
            if (isVip != null) {
                dbUser.setVip(isVip);
            }
            //消息里面不能改OaVerified
            if (avatarChange || nameChange || vipChange) {
                userDao.saveFromMessage(dbUser, isVoip);
            }
        }

        if (avatarChange)
            UserChangeNotifier.getInstance().notifyAvatarChange(uidStr, dbUser.getAvatarUrl());
        if (vipChange)
            UserChangeNotifier.getInstance().notifyVipChange(uidStr, isVip);

        boolean disableSocket = params != null && params.getBoolean(BConstant.Push.FORCE_HTTP, false);

        // 获取头像信息
        if (!bNeedGetProfile || disableSocket) {
            return;
        }

        syncUserSimpleProfile(user.getUserId());
    }


    static void syncUserSimpleProfile(long uid) {
        VLog.i("TAG_USER_TABLE", "syncUserSimpleProfile for %d", uid);
        // 先放到缓存中，延迟1秒后去查询，避免同时发送多个请求
        UserCacheServiceMgr.getInstance().addSyncUid(uid);

    }


    public static UserModel getUser(long uid) {
        UserLogicDao userDao = UserHelper.getUserDBDao();
        if (null == userDao) {
            return null;
        }
        UserModel dbUser = userDao.getUser(uid);
        if (!ContactUtil.isLocalServerId(ValueSafeTransfer.stringValue(uid))) {//本地的server账号不需要向server拉取资料，避免不必要的网络请求
            if ((null == dbUser) || Math.abs(System.currentTimeMillis() - dbUser.getUpdateTime()) > 86400 * 1000) {
                syncUserSimpleProfile(uid);
            }
        }

        return dbUser;
    }

    public static UserModel getUserByUcid(String ucid) {
        UserLogicDao userDao = UserHelper.getUserDBDao();
        if (null == userDao) {
            return null;
        }
        return userDao.getUserByUcid(ucid);
    }

    public static boolean isBabaUser(long uid) {
        UserModel user = UserHelper.getUserModel(uid);
        boolean isBabaUser = user != null && UserHelper.isContactUser(user);
        return isBabaUser;
    }
}
